// ========================= main.c =========================
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

#include "tcpserver.h"
#include "ethercatWindows.h"

static volatile int g_keep = 1;

#ifdef _WIN32
#include <windows.h>
static void sleep_ms_main(int ms) { Sleep(ms); }
BOOL WINAPI console_ctrl(DWORD type)
{
    if (type == CTRL_C_EVENT)
    {
        g_keep = 0;
        return TRUE;
    }
    return FALSE;
}
#else
#include <unistd.h>
static void sleep_ms_main(int ms) { usleep(ms * 1000); }
static void on_sigint(int s)
{
    (void)s;
    g_keep = 0;
}
#endif

int main(int argc, char **argv)
{
    printf("Starting EtherCAT + TCP split demo (Windows-oriented)\n");
#ifdef _WIN32
    SetConsoleCtrlHandler(console_ctrl, TRUE);
#else
    signal(SIGINT, on_sigint);
#endif

    const char *ifname = (argc > 1) ? argv[1] : "\\\\.\\NPCAP_LOOPBACK"; // put your NIC here when using SOEM

    if (ethercatw_start(ifname) != 0)
    {
        fprintf(stderr, "ethercat thread start failed\n");
        return 1;
    }

    if (tcpserver_start() != 0)
    {
        fprintf(stderr, "tcp server failed to start (is port 7070 busy?)\n");
        ethercatw_stop();
        return 2;
    }

    while (g_keep)
    {
        sleep_ms_main(1000); // keep main alive
    }

    tcpserver_stop();
    ethercatw_stop();
    printf("Shutdown complete.\n");
    return 0;
}